//引入的组件
import QuickScreen from "../../components/quick-screen.vue";//快速筛选
import ReplaceCourseware from "../../components/replace-courseware.vue";//替换课件弹窗组件
import OperationLog from "../../components/operation-log.vue";//操作日志弹窗组件
import TreeProject from "@rc/pages/components/async/tree-project.vue";//学员项目树
// 引入api
import coursewareApi from "@rc/apis/rc/courseware.mjs";
//Mixin
import Mixin from '../../mixin/index.mjs';
import editMixin from '../../mixin/edit.mjs';
import filtrate from './filtrate.mjs';

export default {
    name: 'rc-resource-fail',
    components:{
        QuickScreen,
        ReplaceCourseware,
        OperationLog,
        TreeProject
    },
    watch: {
        //当左侧项目树和上方快速搜索区域的初始化之后再去查询列表
        isInitQuickList(val) {
            val && this.onSubmit();
        },
    },
    mixins:[Mixin, editMixin],
    data() {
        return {
            /** 资源列表分页器参数*/
            resourceQueryPagination: {
                pageIndex: 0,
                pageSize: 10,
                pageCount: 0
            },
            /**资源列表 */
            resourceList: [],
            /* 项目，子级项目，科目，章节 */
            chapterInfo: {},
            /* 列表查询加载中*/
            isShowLoading_table: false,
            isShowLoading_quick: false,
            isShowDeleteLoading: false,// 删除课件按钮
            isShowPageLoading: false,// 删除课件按钮
            isShowBatchAuditLoading: false,// 删除课件按钮
            // [学院id,项目id]
            projectArr: [],
            projectId:"",
            // 章节
            checkedKey: '',
            // 快速筛选项
            quickList: [],
            isInitQuickList:false,//快速搜索区域是否初始化
            dialog: {
                isShowReplaceDialog: false,//替换文件弹窗
                isShowLogDialog: false, //日志弹窗
                isShowDeleteDialog: false, //删除资源弹窗
                isShowDeleteDialogResourceTip: false,
                isShowDeleteDialogCardTip: false,
            },
            resourceId:'',//当前替换的课件id
            selectItems: [],//选择的资源
            isCheckedAll: false, //是否全选了
            /* 搜索条件 */
            filtrate: filtrate(this),
            permissArr:[],//权限按钮的显示
            resourceIds:[],//批量审核时的资源id
            pickerMinDate:'',//限制时间范围选择不能超过一年
        };
    },
    created() {
        nlapp.PermissUtil.checkPagePermiss("rc/courseware/audit/fail-list");
        this.permissArr = this.getHasPermissArray();
        this.initQuickList();
    },
    activated() {
        if(this.isInitQuickList) {
            this.permissArr = this.getHasPermissArray();
            if(this.$route.meta.fromPage === 'preview') {
                this.$refs.projectTreeRef.api_getProjectCount();
                this.resourceQueryPagination.pageIndex = this.$route.meta.pageIndex;
                this.onSearchResource();
            } else {
                this.onSubmit();
            }
        }
    },
    methods: {
        //获取权限
        getHasPermissArray(){
            let result = [];
            let PermissArray = [
                {
                    name:'预览',
                    permiss:'rc/courseware/audit/fail-preview',
                    eventName:'onPreview'
                },
                {
                    name:'审核通过',
                    permiss:'rc/courseware/audit/fail-audit',
                    eventName:'handleAudit'
                },
                {
                    name:'编辑',
                    permiss:'rc/courseware/audit/fail-edit',
                    eventName:'editMixin_onEdit'
                },
                {
                    name:'使用详情',
                    permiss:'rc/courseware/audit/fail-detail',
                    eventName:'onResourceDetail'
                },
                {
                    name:'替换课件',
                    permiss:'rc/courseware/audit/fail-replace',
                    eventName:'onClickReplace'
                },

                {
                    name:'删除',
                    permiss:'rc/courseware/audit/fail-delete',
                    eventName:'onDelete'
                },
                {
                    name:'操作日志',
                    permiss:'rc/courseware/audit/fail-log',
                    eventName:'onSearchLog'
                },
            ];
            PermissArray.forEach(permiss=>{
                if(PermissUtil.checkPermiss(permiss.permiss)){
                    result.push(permiss);
                }
            });
            return result;
        },
        //执行点击事件
        handleClick(eventName,resource){
            if(eventName==='onDelete'){
                this[eventName](resource);
            } else {
                this[eventName](resource.resourceId);
            }
        },
         /**
         * 点击快速搜素区域内容，搜索子项
         * @param quickItem
         * @param value
         * @returns
         */
          getChildrenData(quickItem, value) {
            let project = this.$refs.projectTreeRef.api_getCurrentNode();
            if(!project ) {
                this.$message.warning("请先选择项目");
                return;
            }
            if(quickItem.key === 'teachRange' ) {
                this.getSeriesCourse(project.projectId, value);
            }
        },
        /**
         * 初始化快速搜索条件
         */
         initQuickList() {
            this.isShowLoading_quick = true;
            let quickList = [];
            Http.callServices([{
                url: 'rc/admin/common/teachstages', // RC30002 rc/admin/common/teachstages //教学阶段
            },{
                url: 'rc/admin/common/resourcetypes', //RC30001 rc/admin/common/resourcetypes课件分类
            },{
                url: 'rc/admin/common/audit/failure/reasons', //RC30001 rc/admin/common/resourcetypes课件分类
            }
        ]).success((teachRange, livePlaybackState, failReason)=>{
            quickList.splice(quickList.length-1,0,{
                quickName:'课件类型',
                key: 'livePlaybackState',
                type: 'H',
                enumData: livePlaybackState
            },{
                quickName:'不通过原因',
                key: 'auditFailureReason',
                type: 'H',
                enumData: failReason
            },
            {
                quickName:'教学阶段',
                key: 'teachRange',
                type: 'H',
                hasChildren:true,
                enumData: teachRange
            });
            this.quickList = quickList;
         }).complete(()=>{
            this.isShowLoading_quick = false;
         });
        },
        /**
        * 根据项目搜索科目，项目年份
        */
        getSubjectListByProjectId() {
            this.isInitQuickList = false;
            let project = this.$refs.projectTreeRef.api_getCurrentNode();
            this.projectId = project.projectId;
            this.$set(this.$refs.quickScreenRef.quickParams, 'subjectId','');
            this.$set(this.$refs.quickScreenRef.quickParams, 'applicableYearId','');
            this.isShowLoading_quick = true;
            let quickList = this.quickList;
            Http.callServices([{
                url: 'bd/projectyear/list/simple',
                data:{
                    projectId: project.projectId,
                    pageIndex: 0, // 分页数据别删，否则数据可能异常
                    pageSize: 100
                }
            },{
                url: 'bd/subject/list/all',
                data:{
                    projectId: project.projectId,
                    subjectNature: 'S'
                }
            }]).success((yearList, subjectData)=>{
                subjectData = subjectData.data.map(item => ({
                    name: item.subjectName,
                    code: item.subjectId
                }));
                const subjectIndex = quickList.findIndex( item => item.key === 'subjectId');
                if(subjectIndex===-1) {
                    quickList.splice(quickList.length-1,0,{
                        quickName:'科目',
                        key: 'subjectId',
                        type: 'H',
                        enumData: subjectData
                    });
                } else {
                    quickList[subjectIndex].enumData = subjectData;
                }
                yearList = this.sortYear(yearList.data);
                yearList = yearList.map(item => ({
                    name: item.projectyearYear + '年',
                    code: item.projectyearId
                }));
                //const currentYear = new Date().getFullYear();
                const yearIndex = quickList.findIndex( item => item.key === 'applicableYearId');
                const isExists =  yearList.length > 0 ? yearList[0] : '';//yearList.find( item => item.name === currentYear + '年');
                const defaultYear = isExists ? isExists.code : '';
                this.$refs.quickScreenRef && this.$set(this.$refs.quickScreenRef.quickParams, 'applicableYearId', defaultYear);
                if(yearIndex===-1) {
                    quickList.push({
                        quickName:'年份',
                        key: 'applicableYearId',
                        type: 'H',
                        enumData: yearList,
                        default: defaultYear
                    });
                } else {
                    quickList[yearIndex].enumData = yearList;
                    quickList[yearIndex].default =  defaultYear;
                }
                this.quickList = quickList;
            }).complete(() => {
                if(!this.isInitQuickList) {
                    this.isInitQuickList = true;
                }
                this.isShowLoading_quick = false;
            });
        },
        /**
         * 批量审核按钮
         */
         batchCheckResourceVideo(){
            if (!this.selectIds.length) {
				this.$message.warning("请先选择课件!");
				return;
			}
            this.$confirm('确认审核通过?', '审核提醒', {
                confirmButtonText: '审核通过',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.resourceIds = this.selectIds;
                this.isShowBatchAuditLoading = true;
                coursewareApi.batchCheckResourceVideo({
                    data: {
                        resourceIds: this.resourceIds,
                        checkState: 'P',
                        oldCheckState: this.oldCheckState //待审核
                    },
                    success: () => {
                        this.$message.success('审核操作成功');
                        this.$emit('success');
                        this.onSubmit();
                    },
                    complete: () => {
                        this.isShowBatchAuditLoading = false;
                    }
                });
            });

        },
        onSubmit() {
            this.$refs.projectTreeRef.api_getProjectCount();
            this.resourceQueryPagination.pageIndex = 0;
            this.onSearchResource();
        },
        /**
         * 搜索获取资源列表
         */
        onSearchResource() {

            this.isCheckedAll = false;
            this.selectItems = [];

            let params = {};
            // -------拼接参数----开始
            //项目
            let project = this.$refs.projectTreeRef.api_getCurrentNode();
            if(!project) {
                this.$message.warning("请先选择项目");
                return;
            }
            this.resourceList = [];
            this.isShowLoading_table = true;
            //快速搜索区域参数
            const quickList = this.quickList;
            const notlableParams = quickList.filter( item => !item.isLabel);
            const quickParams = this.$refs.quickScreenRef.quickParams;
            let quickListParams = {};
            //快速搜索区域-非标签参数
            notlableParams.forEach(param => {
                quickListParams[param.key] = quickParams[param.key] || '';
            });
            const searchParams = this.$refs.veFiltrate.getResult();

            // 处理上传时间
            if(searchParams.uploadDate){
                const {start,end} = searchParams.uploadDate;
                searchParams.uploadStarTime= start?start+" 00:00:00":'';
                searchParams.uploadEndTime= end?end+" 23:59:59":'';

            } else { //默认最近一周
                searchParams.uploadStarTime= this.formatDateStart(this.beforeWeek())+" 00:00:00";
                searchParams.uploadEndTime= this.formatDateNow(new Date)+" 23:59:59";
            }
            delete searchParams.uploadDate;
            params = {
                projectId: project.projectId,
                ...quickListParams,
                ...searchParams,
                auditStatus: 'N',//审核不通过
                pageIndex: PageUtil.getStartIndex(this.resourceQueryPagination),
                pageSize: this.resourceQueryPagination.pageSize,
            };
             // -------拼接参数----结束
            //调用接口
            coursewareApi.queryPendResourceVideoList({
                data: {
                    ...params
                },
                success: (result) => {
                    this.resourceList = result.data;
                    this.$set(this.resourceQueryPagination,'pageCount', result.count);
                },
                complete:(()=>{
                    this.isShowLoading_table = false;
                })
            });
        },
        /**
         * 项目切换
         */
         onChooseProject() {
            this.getSubjectListByProjectId();
            const teachRange = this.$refs.quickScreenRef.quickParams.teachRange;
            this.getChildrenData({
                key :'teachRange',
            }, teachRange);
        }
    }
};
